<?php

namespace App\Admin\Actions\Audit;

use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ShopUserLogic;
use App\Models\InviteCertificationModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Exception;
use Illuminate\Http\Request;

class AuditInviteCertificationAction extends RowAction
{
    public $name = '审核';

    /**
     * handle
     * @param InviteCertificationModel $model
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function handle(InviteCertificationModel $model, Request $request): Response
    {
        //if (is_null($model)) return $this->response()->error(__('errorCode.433'))->refresh();
        if ($model->status !== 0) return $this->response()->error(__('errorCode.633'))->refresh();
        else if (is_null($model->userInfo)) return $this->response()->error(__('errorCode.433'))->refresh();
        $model->status = $request->status;
        if ((int)$request->status === 1) $model->ok_reason = is_null($request->reason) ? '' : $request->reason;
        else $model->fail_reason = is_null($request->reason) ? '' : $request->reason;
        $model->save();
        $inviteCode = random();
        while (!ShopUserLogic::existsByWhere('inviteCode', $inviteCode)) {
            $model->userInfo->invite_code = $inviteCode;
            $model->userInfo->save();
            mq('cacheUser', (string)$model->userInfo->user_id);
        }
        OperateLogLogic::add(Admin::user()->user_id, 'admin.inviteCertification.audit');
        return $this->response()->success('操作成功！')->refresh();
    }

    public function form(): void
    {
        $this->select('status', '审核')->options([1 => '同意', 2 => '拒绝'])->default(2)->required();
        $this->textarea('reason', '原因')->rules('nullable|string|max:255');
    }

    public function html(): string
    {
        return "<a class='report-posts btn btn-sm btn-danger'><i class='fa fa-info-circle'></i>确认</a>";
    }
}
